package com.cnswhy.cloud.server.merchant.util;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class OssUtils {
    public static String updateLoadFileToOss(String userId, String imageUrl, String fileName) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。http://oss-cn-hangzhou.aliyuncs.com
        String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 http://ram.console.aliyun.com 创建RAM账号。

        String accessKeyId = "LTAIlBFDDNv8oSjE";
        String accessKeySecret = "BwRCJaY2QwAFDkSG5twZhJkp3FQNjr";
        String bucketName="leyoutuan";
        fileName=userId + fileName;
        String Url="http://lyt.hechuang8.com/"+fileName;
        InputStream inputStream = null;

        try {

            if (imageUrl != null && imageUrl.startsWith("http"))//从url中获取文件
            {
                log.info(imageUrl);
                URL url = new URL(imageUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置超时间为6秒
                conn.setConnectTimeout(6 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                try {
                    inputStream = conn.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception ex) {
            log.error("加载异常:{}", ex.toString());
            return null;
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("加载异常:{}", e);
                }
            }
        }
        return Url;
    }
}
